/// 消息输入组件
/// 用于输入和发送消息
library;
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:chat_project/config/theme_config.dart';

typedef MessageCallback = void Function(String content, String type);
typedef TypingCallback = void Function(bool isTyping);

class MessageInput extends StatefulWidget {
  final MessageCallback onSend;
  final TypingCallback onTypingChanged;
  final bool isLoading;
  
  const MessageInput({
    super.key,
    required this.onSend,
    required this.onTypingChanged,
    this.isLoading = false,
  });

  @override
  State<MessageInput> createState() => _MessageInputState();
}

class _MessageInputState extends State<MessageInput> {
  final TextEditingController _controller = TextEditingController();
  bool _isComposing = false;
  final ImagePicker _imagePicker = ImagePicker();
  bool _showAttachOptions = false;
  
  @override
  void initState() {
    super.initState();
    _controller.addListener(_onTextChanged);
  }
  
  @override
  void dispose() {
    _controller.removeListener(_onTextChanged);
    _controller.dispose();
    super.dispose();
  }
  
  // 文本变化回调
  void _onTextChanged() {
    setState(() {
      _isComposing = _controller.text.isNotEmpty;
    });
    
    widget.onTypingChanged(_isComposing);
  }
  
  // 发送文本消息
  void _handleSubmitted() {
    final text = _controller.text.trim();
    if (text.isEmpty) return;
    
    widget.onSend(text, 'text');
    _controller.clear();
    
    // 重置输入状态
    setState(() {
      _isComposing = false;
      _showAttachOptions = false;
    });
    
    widget.onTypingChanged(false);
  }
  
  // 选择图片
  Future<void> _pickImage(ImageSource source) async {
    try {
      final pickedFile = await _imagePicker.pickImage(
        source: source,
        imageQuality: 70,
      );
      
      if (pickedFile != null) {
        // 发送图片消息
        widget.onSend(pickedFile.path, 'image');
      }
      
      // 隐藏附件选项
      setState(() {
        _showAttachOptions = false;
      });
    } catch (e) {
      print('选择图片错误: $e');
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 输入区域
        Container(
          decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.05),
                offset: const Offset(0, -1),
                blurRadius: 5,
              ),
            ],
          ),
          padding: const EdgeInsets.symmetric(
            horizontal: ThemeConfig.paddingRegular,
            vertical: ThemeConfig.paddingSmall,
          ),
          child: SafeArea(
            child: Row(
              children: [
                // 附件按钮
                IconButton(
                  icon: Icon(
                    _showAttachOptions ? Icons.close : Icons.attach_file,
                    color: _showAttachOptions 
                        ? ThemeConfig.primaryColor 
                        : ThemeConfig.textSecondaryColor,
                  ),
                  onPressed: () {
                    setState(() {
                      _showAttachOptions = !_showAttachOptions;
                    });
                  },
                ),
                
                // 输入框
                Expanded(
                  child: TextField(
                    controller: _controller,
                    decoration: InputDecoration(
                      hintText: '输入消息...',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(
                          ThemeConfig.borderRadiusRound,
                        ),
                        borderSide: BorderSide.none,
                      ),
                      filled: true,
                      fillColor: Colors.grey[100],
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: ThemeConfig.paddingRegular,
                        vertical: ThemeConfig.paddingSmall,
                      ),
                    ),
                    textInputAction: TextInputAction.send,
                    onSubmitted: (_) => _handleSubmitted(),
                    maxLines: 4,
                    minLines: 1,
                  ),
                ),
                
                // 发送按钮
                IconButton(
                  icon: widget.isLoading
                      ? const SizedBox(
                          width: 24,
                          height: 24,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            color: ThemeConfig.primaryColor,
                          ),
                        )
                      : Icon(
                          _isComposing ? Icons.send : Icons.mic,
                          color: _isComposing 
                              ? ThemeConfig.primaryColor 
                              : ThemeConfig.textSecondaryColor,
                        ),
                  onPressed: widget.isLoading
                      ? null
                      : _isComposing 
                          ? _handleSubmitted 
                          : () {}, // 这里可以添加语音消息功能
                ),
              ],
            ),
          ),
        ),
        
        // 附件选项
        if (_showAttachOptions)
          _buildAttachOptions(),
      ],
    );
  }
  
  // 构建附件选项
  Widget _buildAttachOptions() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.all(ThemeConfig.paddingRegular),
      child: SafeArea(
        top: false,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            _buildAttachOption(
              icon: Icons.photo,
              label: '相册',
              color: Colors.purple,
              onTap: () => _pickImage(ImageSource.gallery),
            ),
            _buildAttachOption(
              icon: Icons.camera_alt,
              label: '相机',
              color: Colors.red,
              onTap: () => _pickImage(ImageSource.camera),
            ),
            _buildAttachOption(
              icon: Icons.insert_drive_file,
              label: '文件',
              color: Colors.blue,
              onTap: () {
                // 处理文件选择逻辑
              },
            ),
            _buildAttachOption(
              icon: Icons.location_on,
              label: '位置',
              color: Colors.green,
              onTap: () {
                // 处理位置选择逻辑
              },
            ),
          ],
        ),
      ),
    );
  }
  
  // 构建单个附件选项
  Widget _buildAttachOption({
    required IconData icon,
    required String label,
    required Color color,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 60,
            height: 60,
            decoration: BoxDecoration(
              color: color.withOpacity(0.1),
              shape: BoxShape.circle,
            ),
            child: Icon(
              icon,
              color: color,
              size: 30,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            label,
            style: const TextStyle(
              fontSize: ThemeConfig.fontSizeSmall,
              color: ThemeConfig.textSecondaryColor,
            ),
          ),
        ],
      ),
    );
  }
} 